import React, { Component } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Row,
  Col,
  Card,
  Table,
  Button,
  Input,
  Select,
  Divider,
  Modal,
  Tooltip,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

import { TableListData } from './data';

const { Option } = Select;
const { pathname } = window.location;

interface PackagePricesListProps extends FormComponentProps {
  dispatch: Dispatch;
  loading: boolean;
  dataInfo: TableListData;
  INITINFO: any;
  screen: string;
  hasPath: boolean;
}

interface PackagePricesListState {
  searchValues: any;
  statusVisible: boolean;
  pageIndex:number;
  pageSize:number;
  rowId:number;
  statusValues: {
    id: number | string;
    status: number;
  }
}

@connect(({
  packagePricesList: { dataInfo },
  common: { INITINFO },
  global: { screen, hasPath },
  loading,
}: any) => ({
  dataInfo,
  INITINFO,
  screen,
  hasPath,
  loading: loading.effects['packagePricesList/fetch'],
}))

class PackagePricesListElem extends Component<PackagePricesListProps, PackagePricesListState> {
  columns: any = [
    {
      title: '物流中心',
      dataIndex: 'logisName',
      width: 180,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div
            className="wordOmit nameLink"
            onClick={() => this.handleEditOrCopyPackagePrices(record.id, 1)}
          >
            {text}
          </div>
        </Tooltip>
      ),
    },
    {
      title: '快递公司',
      dataIndex: 'expressName',
      width: 100,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '计费方式(内)',
      dataIndex: 'chargeTypeName',
      width: 120,
      render: (text: string) => text || '--',
    },
    {
      title: '单价(内)',
      dataIndex: 'unitPrice',
      width: 100,
      render: (text: number) => (
        text ? (text / 100).toFixed(2) : '0.00'
      ),
    },
    {
      title: '校外派件',
      dataIndex: 'isOutSchool',
      width: 100,
      render: (text: number) => (
        text ? '是' : '否'
      ),
    },
    {
      title: '计费方式(外)',
      dataIndex: 'outChargeTypeName',
      width: 120,
      render: (text: string) => text || '--',
    },
    {
      title: '单价(外)',
      dataIndex: 'outUnitPrice',
      width: 100,
      render: (text: number) => (
        text ? (text / 100).toFixed(2) : '0.00'
      ),
    },
    { title: '状态', dataIndex: 'statusTxt', width: 100 },
    {
      title: '结算方式',
      dataIndex: 'settleWayName',
      width: 120,
      render: (text: string) => text || '--',
    },
    {
      title: '合同编号',
      dataIndex: 'contractCode',
      width: 200,
      render: (text: string, record: any) => (
        <Tooltip title={text}>
          <div className="wordOmit">{text}</div>
        </Tooltip>
      ),
    },
    {
      title: '合同时间',
      dataIndex: 'startTime',
      width: 220,
      render: (val: string, row: any) => (
        <span style={{ whiteSpace: 'normal' }}>
          {row.startTime.split(' ')[0]}~{row.endTime.split(' ')[0]}
        </span>
      ),
    },
    { title: '操作人', dataIndex: 'updateUserName', width: 100 },
    {
      title: '操作',
      fixed: 'right',
      width: 180,
      render: (val: any, record: any) => (
        <>
          <span
            className="operLink"
            onClick={() => this.handleEditOrCopyPackagePrices(record.id, 1)}
          >
            编辑
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.handleEditOrCopyPackagePrices(record.id, 2)}
          >
            复制
          </span>
          <Divider type="vertical" />
          <span
            className="operLink"
            onClick={() => this.setChangeStatusModal(true, record)}
          >设置无效
          </span>
        </>
      ),
    },
  ]

  state: PackagePricesListState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    statusVisible: false,
    rowId: 0,
    statusValues: { id: '', status: 0 },
  }

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchAction('common/fetchLogisList');

    const { dataInfo, hasPath } = this.props;
    if (dataInfo?.list?.length && !hasPath) return;
    if (hasPath) {
      const { dispatch } = this.props;
      dispatch({ type: 'global/clearPath' });
    }

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => { // 设置表单
    const { searchValues } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(searchValues);
  }

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };
    return params;
  }

  /**
   * 新建派件资费配置
   */
  handleAddPackagePrices = () => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '新建派件资费配置',
      url: '/basic/packagePrices/list/add',
    });
  }

  /**
   * 编辑/复制派件资费配置
   */
  handleEditOrCopyPackagePrices = (id: number, type: number) => {
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: type === 1 ? '编辑资费' : '复制资费',
      url: `/basic/packagePrices/list/add?id=${id}&type=${type}`,
    });
  }

  setChangeStatusModal = (statusVisible: boolean, row?: any) => {
    this.setState({
      statusVisible,
      statusValues: {
        id: row ? row.id : '',
        status: 0,
      },
    });
  }

  handleSetStatus = () => {
    const { statusValues, searchValues: search } = this.state;
    const params = { search, ...statusValues };
    this.fetchAction('change', params);
    this.setChangeStatusModal(false);
  }

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const query = {
        ...values,
        pageIndex: 1,
        pageSize: 20,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '派件资费管理',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  }

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '派件资费管理',
      url: pathname,
      isTopMenu: true,
    });
  }

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '派件资费管理',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  }

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = typeName.indexOf('common') >= 0
      ? typeName : `packagePricesList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({
      type,
      payload,
    });
  }

  render() {
    const {
      pageIndex,
      pageSize,
      statusVisible,
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
      INITINFO: { logisList },
      loading,
      screen,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];

    const pagination: object = dataInfo
      ? {
        total: dataInfo.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${dataInfo.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    if (screen === 'sm') {
      delete this.columns[this.columns.length - 1].fixed;
    } else if (screen === 'md' || screen === 'lg') {
      this.columns[this.columns.length - 1].fixed = 'right';
    }

    return (
      <>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId')(
                    <Select
                      showSearch
                      allowClear
                      placeholder="请选择"
                      filterOption={(input: any, option: any) => (
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      )}
                    >
                      {logisList.map((item: any) => (
                        <Option value={String(item.id)} key={item.id}>{item.name}</Option>
                      ))}
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="合同编号" colon={false}>
                  {getFieldDecorator('contractCode')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="　　状态" colon={false}>
                  {getFieldDecorator('status')(
                    <Select allowClear placeholder="请选择">
                      <Option value="1">正常</Option>
                      <Option value="0">无效</Option>
                    </Select>,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24} className="flexFeView">
                <Button
                  type="primary"
                  htmlType="submit"
                  className="smallButton"
                >
                  查询
                </Button>
                <Button
                  type="primary"
                  className="addButton smallButton marginL16"
                  onClick={this.handleReset}
                >
                  重置
                </Button>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          <div className="tableBtns">
            <Button
              type="primary"
              size="small"
              className="smallButton"
              onClick={this.handleAddPackagePrices}
            >
              新建派件资费配置
            </Button>
          </div>
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
            loading={loading}
            scroll={{ x: 1500 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <Modal
          visible={statusVisible}
          title="设置无效"
          onOk={this.handleSetStatus}
          onCancel={() => this.setChangeStatusModal(false)}
        >
          <p>确定设置无效？</p>
        </Modal>
      </>
    );
  }
}

export default Form.create<PackagePricesListProps>()(PackagePricesListElem);
